package com.eastfair.notice.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.eastfair.notice.dto.MsgSendDTO;
import com.eastfair.annotation.base.LanguageTypeEnum;
import com.eastfair.enums.MsgTypeEnum;
import com.eastfair.notice.dto.MsgMqDTO;
import com.eastfair.notice.entity.MsgLog;
import com.eastfair.notice.service.MsgLogService;
import com.eastfair.projectcore.entity.MsgTemplate;
import com.eastfair.third.model.MessageResult;
import com.eastfair.third.sms.SmsUtil;
import com.eastfair.third.sms.model.Message;
import com.eastfair.third.sms.model.SmsConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

/**
 * 短信发送mq消费
 * @ClassName SmsSendListener
 * @Description 短信发送mq消费
 * @Author liuxiaobai
 * @Date 2021/8/7 2:55 下午
 * @Version 1.0
 */
@Component
public class SmsSendListener {
    private static final Logger logger = LoggerFactory.getLogger(SmsSendListener.class);

    @Autowired
    private MsgLogService msgLogService;

    @JmsListener(destination = "${activemq.queue.smsSend}")
    public void handleMessage(String json) {
        try {
            MsgMqDTO mqDTO = JSON.parseObject(json, MsgMqDTO.class);
            SmsConfig config = mqDTO.getSmsConfig();
            MsgSendDTO sendDTO = mqDTO.getMsgSendDTO();
            MsgTemplate template = mqDTO.getTemplate();
            if (sendDTO == null || template == null) {
                return;
            }
            String receive = sendDTO.getMobile();
            if (StrUtil.isEmpty(receive)) {
                return;
            }
            //发短信组件所需参数
            Message message = Message.builder()
                    .projectId(sendDTO.getProjectId())
                    .content(LanguageTypeEnum.CN.equals(sendDTO.getLanguageType()) ? template.getContent() : template.getEnContent())
                    .sign(sendDTO.getSign())
                    .build();

            message.setMobile(receive);
            MessageResult result = SmsUtil.sendMessage(config,message);
            //加入日志
            msgLogService.save(MsgLog.builder()
                    .projectId(sendDTO.getProjectId())
                    .exhibitionId(sendDTO.getExhibitionId())
                    .type(MsgTypeEnum.SMS.name())
                    .tempId(template.getId())
                    .receiveType(sendDTO.getReceiveType().name())
                    .receiveId(sendDTO.getReceiveUserId())
                    .receive(receive)
                    .content(message.getContent())
                    .status(result.getStatus())
                    .errMsg(result.getErrorMsg())
                    .build());
        } catch (Exception e) {
            logger.error("短信mq消费",e);
        }
    }

}
